﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQuarters.WebQuarters.Core;
using OpenQuarters.WebQuarters.Utils;
using OpenQuarters.WebQuarters.Modules.ItemList;
using RssToolkit.Rss;

namespace OpenQuarters.WebQuarters.Modules.Articles
{
    [QueryableListProviderContainerAttribute]
    partial class Article : ArticleEntity<Article, long>, IItemListable
    {
        public override long GetKey(Article Entity)
        {
            return Entity.ArticleId;
        }

        public override System.Linq.Expressions.Expression<Func<Article, bool>> GetIDSelector(long ID)
        {
            return e => e.ArticleId == ID;
        }

        public override string ToString()
        {
            return this.Title;
        }

        partial void OnTitleChanged()
        {
            if (this.Title != this.Title.StripHTML())
            {
                this.Title = this.Title.StripHTML();
            }
        }

        [Filterable, Orderable, Searchable]
        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox, SourceField = "Title")]
        public string json_Title
        {
            get { return this.Title; }
            set { this.Title = value; }
        }

        [Newtonsoft.Json.JsonProperty, Searchable]
        [PropertyConfiguration(PropertyType.TextArea, SourceField = "Summary")]
        public string json_Summary
        {
            get { return this.Summary; }
            set { this.Summary = value; }
        }

        [Filterable, Orderable]
        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox, SourceField = "LanguageId")]
        public string json_LanguageId
        {
            get { return this.LanguageId; }
            set { this.LanguageId = value; }
        }

        [Filterable, Orderable, Searchable]
        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextArea, SourceField = "Keywords")]
        public string json_Keywords
        {
            get { return this.Keywords; }
            set { this.Keywords = value; }
        }

        [Filterable, Orderable, Searchable]
        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DatePicker, SourceField = "DateCreated")]
        public DateTime json_Date_Created
        {
            get { return this.DateCreated; }
            set { this.DateCreated = value; }
        }

        [Filterable, Orderable]
        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.CheckBox, SourceField = "IsLive")]
        public bool json_IsLive
        {
            get { return this.IsLive; }
            set { this.IsLive = value; }
        }

        [Filterable, Orderable, Searchable]
        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox, SourceField = "Category")]
        public string json_Category
        {
            get { return this.Category; }
            set { this.Category = value; }
        }

        [Searchable]
        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextArea, SourceField = "Content")]
        public string json_Content
        {
            get { return this.Content; }
            set { this.Content = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.Image, SourceField = "ThumbnailPath")]
        public string json_ThumbnailPath
        {
            get { return this.ThumbnailPath; }
            set { this.ThumbnailPath = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.Hidden, SourceField = "ArticleId")]
        public long json_ArticleId
        {
            get { return this.ArticleId; }
            set { this.ArticleId = value; }
        }

        [Orderable]
        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox, SourceField = "Order")]
        public int json_Order
        {
            get { return this.Order; }
            set { this.Order = value; }
        }

        [Url]
        [Newtonsoft.Json.JsonProperty]
        public string Url
        {
            get
            {
                return this.ItemUrl();
            }
        }

        public string ItemUrl()
        {
            StringBuilder sb = new StringBuilder();
            if (ItemListerHelper.CurrentFullViewPage != null && ItemListerHelper.CurrentFullViewPage.CurrentVersion != null)
            {
                sb.Append(ItemListerHelper.CurrentFullViewPage.GetUrl() + "/");
            }
            sb.Append(this.DateCreated.Year.ToString() + "/" + this.DateCreated.Month.ToString().PadLeft(2, Char.Parse("0")) + "/" + this.DateCreated.Day.ToString().PadLeft(2, Char.Parse("0")) + "/");
            if (Title != null)
            {
                sb.Append(Title.ToUrlSafeString());
            }
            return sb.ToString();
        }

        [Newtonsoft.Json.JsonProperty]
        public string HtmlLink
        {
            get
            {
                return @"<a href=""" + this.ItemUrl() + @""">" + Title + "</a>";
            }
        }

        public string EditLink
        {
            get
            {
                return ItemListModule.GetItemEditLink(this);
            }
        }

        public string DeleteLink
        {
            get
            {
                return ItemListModule.GetItemDeleteLink(this);
            }
        }

        [Newtonsoft.Json.JsonProperty]
        public string BackLink
        {
            get
            {
                return GetBackLink(Core.Translation.Translate("Back"));
            }
        }

        public string GetBackLink(string text)
        {
            return @"<a href=""" + ItemListerHelper.CurrentFullViewPage.GetUrl() + @""">" + text + "</a>";
        }

        public override void OnSaving()
        {
            base.OnSaving();

            if (this.DateCreated == DateTime.MinValue)
            {
                this.DateCreated = DateTime.Now;
            }
        }

        #region IItemListable Members

        public bool IsNewItem()
        {
            return IsNew();
        }

        public IItemListable LoadItem(string ID)
        {
            return Load(ID.ToInt64());
        }

        public IItemListable SaveItem()
        {
            return this.Save();
        }

        public void DeleteItem()
        {
            this.Delete();
        }

        public string GetIDAsString()
        {
            return this.ArticleId.ToString();
        }

        public IItemListable CreateItem<T>(ItemListerControl<T> parentList) where T : class, IItemListable
        {
            return new Article()
            {
                Title = "New Article Title",
                Summary = "Article Summary",
                Content = "<p>Article Content</p>",
                DateCreated = DateTime.Now,
                IsLive = false,
                LanguageId = Language.Current.LanguageId,
                Category = "", 
                Order = (Table.Count() != 0 ? (Table.Max(a => (Int32?)a.Order)?? 0) + 5 : 0)
            };
        }

        public IQueryable GetQueryableList()
        {
            return DataContext.GetTable<Article>();
        }

        [QueryableListProvider]
        public static IQueryable<Article> GetLiveArticles()
        {
            return DataContext.GetTable<Article>().Where(a => a.IsLive == true);
        }

        [QueryableListProvider]
        public static IQueryable<Article> GetAllArticles()
        {
            return DataContext.GetTable<Article>();
        }

        public IItemListable GetItemFromUrl(string url, List<IItemListable> additionalItems)
        {
            try
            {
                foreach (var i in additionalItems)
                {
                    if (url.EndsWith(((Article)i).ItemUrl()))
                    {
                        return i;
                    }
                }

                List<string> urlParts = url.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                DateTime dateCreated = new DateTime(
                    Convert.ToInt32(urlParts[urlParts.Count - 4]),
                    Convert.ToInt32(urlParts[urlParts.Count - 3]),
                    Convert.ToInt32(urlParts[urlParts.Count - 2]));
                DateTime dateCreatedEnd = dateCreated.AddDays(1);

                var matchingDates = Table.Where(i => i.DateCreated >= dateCreated && i.DateCreated < dateCreatedEnd);
                foreach (var i in matchingDates)
                {
                    if (i.Title.ToUrlSafeString() == urlParts.Last())
                    {
                        return i;
                    }
                }
            }
            catch { }
            return null;
        }


        public RssToolkit.Rss.RssItem ToRssItem()
        {
            RssItem item = new RssItem();
            item.Title = this.Title;
            item.PubDateParsed = this.DateCreated;
            item.Description = this.Content;
            item.Link = this.ItemUrl();

            if (this.Category.Length != 0)
            {
                RssCategory category = new RssCategory();
                category.Text = this.Category;
                item.Categories = new List<RssCategory>();
                item.Categories.Add(category);
            }

            return item;
        }

        public string ItemTitle()
        {
            return this.Title;
        }

        public string MetaKeywords()
        {
            return this.Keywords;
        }

        public string MetaDescription()
        {
            return this.Summary;
        }

        #endregion
    }
}
